import redis

import random
from concurrent.futures import ThreadPoolExecutor

from db.redis_db import pool

# 生成1000随机id
user_ids = set()
while True:
    if len(user_ids) >= 1000:
        break
    id = random.randint(1000, 10000)
    user_ids.add(id)


def buy():
    con = redis.Redis(connection_pool=pool)
    pipeline = con.pipeline()
    try:
        if con.exists("kill_flag") == 1:
            pipeline.watch("kill_count", "kill_ids")
            kill_total = int(pipeline.get("kill_total"))
            kill_count = int(pipeline.get("kill_count"))
            if kill_count < kill_total:
                pipeline.multi()
                pipeline.incr("kill_count")
                pipeline.rpush("kill_ids", user_ids.pop())
                pipeline.execute()
    except Exception as e:
        print(e)
    finally:
        if "pipeline" in dir():
            pipeline.reset()
        del con


try:
    con = redis.Redis(connection_pool=pool)
    con.delete("kill_total", "kill_count", "kill_flag", "kill_ids")
    con.set("kill_total", 100)
    con.set("kill_count", 0)
    con.set("kill_flag", 1, ex=600)
    with ThreadPoolExecutor(max_workers=100) as th:
        for i in range(0, 100):
            th.submit(buy)

except Exception as e:
    print(e)
finally:
    del con
